use std::process::Command;
use axum::Json;
use serde_json::{Value, json};
use crate::code;

pub fn cmd(order:&str) -> Json<Value>{
    let result =  Command::new("cmd")
    .args(["/C",order])
    // .current_dir("E:/gitee/rust-wuye")
    .output();

    match result {
        Ok(f) => code::data_( json!({ "stdout":String::from_utf8_lossy(&f.stdout), "cmd": order }) ),
        Err(e) => code::sys_(e.to_string())
    }
}

pub async fn cmd_spawn(order:&str) -> Result<Json<Value>, Json<Value>>{
    match Command::new("cmd").args(["/C",order]).spawn() {
        Ok(child) => {
            let mut rs = json!({});
            let mut er = json!({});
            let result = tokio::spawn(async move {  
                match child.wait_with_output() {
                    Ok(t) => {
                        rs["status"] = json!(t.status.to_string());
                        rs["stdout"] = json!(t.stdout);
                        rs["stderr"] = json!(t.stderr);
                        rs
                    },
                    Err(e) => {
                        er["err"] = json!(&e.to_string());
                        er
                    }
                }
            }).await;
            match result {
                Ok(f) =>{
                    if let Some( f ) = f.as_object() {
                        if let Some(t) = f.get("err"){
                            code::err(t.as_str().unwrap_or_default())
                        }else{
                            code::data(json!(f))
                        }
                    }else{
                        code::err("未知错误")
                    }
                },
                Err(e) => code::sys(e.to_string())
            }
        },
        Err(e) => code::sys(e.to_string())
    }
}